/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.example.zhpan.bannerviewpager.adapter;

import ohos.agp.components.AttrHelper;
import ohos.agp.components.element.PixelMapElement;
import ohos.app.Context;
import ohos.global.resource.NotExistException;
import ohos.media.image.ImageSource;
import ohos.media.image.common.Size;

import com.zhpan.bannerview.Log;

import java.io.IOException;
import java.io.InputStream;

/**
 * Untils
 *
 * @since 2021-03-24
 */
public class Untils {
    static PixelMapElement pixelMapElement = null;
    private static final float TWOTYFIVE = 25.0f;

    /**
     * Untils
     */
    private Untils() {
    }

    /**
     * PixelMapElement
     *
     * @param resId 參數
     * @param context 參數
     * @return pixelMapElement
     */
    public static PixelMapElement getBitmap(Integer resId, Context context) {
        if (resId <= 0) {
            return pixelMapElement;
        }
        InputStream is = null;
        try {
            is = context.getResourceManager().getResource(resId); // 读取资源
            ImageSource.SourceOptions sourceOptions = new ImageSource.SourceOptions(); // 创建ImageOptions
            sourceOptions.formatHint = "image/jpg";
            ImageSource imageSource = ImageSource.create(is, sourceOptions); // 创建ImageSource
            ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions(); // 创建解码器DecodingOptions
            decodingOptions.desiredSize = new Size(AttrHelper.vp2px(TWOTYFIVE, context),
                AttrHelper.vp2px(TWOTYFIVE, context));
            return new PixelMapElement(imageSource.createPixelmap(decodingOptions)); // 创建mapX
        } catch (IOException | NotExistException e) {
            Log.debug(e.getMessage());
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                Log.debug(e.getMessage());
            }
        }
        return pixelMapElement;
    }
}
